<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import { Search, RefreshLeft } from '@element-plus/icons-vue'
import {
  ElTableColumn,
  ElTable,
  ElPagination,
  ElCol,
  ElRow,
  ElCheckbox,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElSelect,
  ElOption
} from 'element-plus'
import type { FormInstance } from 'element-plus'

import { sysDictRelsApi } from '@/api/dict'
import { zcAssetListAdminApi } from '@/api/cy/zichan'
// import { Form } from '@/components/Form'

import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

const dictRelsData = ref() // 联动数据

const ruleFormRef = ref<FormInstance>()

let allCheck = ref(false)
let selectData = ref([])
let noSelectData = ref([])
const total = ref(0)
let num = ref(0)
const props = defineProps({
  id: {
    type: String,
    default: () => null
  },
  breed: {
    type: String,
    default: () => null
  },
  breedSub: {
    type: String,
    default: () => null
  },
  selectData: {
    type: Array,
    default: () => null
  },
  allCheck: {
    type: Boolean,
    default: () => null
  }
})
console.log(props, 'id')
// console.log(props.selectData, 'selectData')
let assetsData = ref([])
const multipleTable = ref<InstanceType<typeof ElTable>>()

const page = ref(1)
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const disabled = ref(false)
const breedSubData = ref([])
// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

// 选择畜别的时候触发，处理品种类容
const breedChange = async (value) => {
  ruleForm.bread_sub = ''
  await breedGetSub(value)
  // let formData = await methods.getFormData()
  // await methods.setValues({ ...formData, breed_sub: '' })
}
const getList = async (val) => {
  let res
  if (val) {
    res = await zcAssetListAdminApi({
      my_org_id: '1',
      select_type: '2',
      breed: props.breed,
      pasture_org_id: props.id,
      pageSize: pageSize4.value,
      pageNo: page.value,
      bread_sub: props.breedSub
    })
      .catch(() => {})
      .finally(() => {})
  } else {
    res = await zcAssetListAdminApi({
      my_org_id: '1',
      select_type: '2',
      pasture_org_id: props.id,
      pageSize: pageSize4.value,
      pageNo: page.value,
      breed: props.breed,
      breed_sub: props.breedSub
    })
      .catch(() => {})
      .finally(() => {})
  }

  if (res) {
    assetsData.value = res.data
    total.value = res.count
    // allCheck.value = props.allCheck
    // console.log(props.allCheck, 'allCheck.value')
    setTimeout(() => {
      if (allCheck.value) {
        num.value = total.value - props.selectData.length
        let newArr = assetsData.value.filter(
          (x) => !noSelectData.value.some((item) => x.id === item.id)
        )
        newArr.forEach((row) => {
          multipleTable.value.toggleRowSelection(row, true)
        })
      } else {
        setTimeout(() => {
          // selectData.value.forEach((row) => {
          //   multipleTable.value.toggleRowSelection(row, true)
          // })
        }, 0)
      }
    }, 0)
  }
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

const init = async () => {
  // 获取关联关系
  await getDictRels()
  // 列表查询
  allCheck.value = props.allCheck
  if (allCheck.value) {
    await getList()
    noSelectData.value = props.selectData
    if (noSelectData.value.length > 0) {
      // 去重
      let newArr = assetsData.value.filter(
        (x) => !noSelectData.value.some((item) => x.id === item.id)
      )
      newArr.forEach((row) => {
        multipleTable.value.toggleRowSelection(row, true)
      })
    } else {
      assetsData.value.forEach((row) => {
        multipleTable.value.toggleRowSelection(row, true)
      })
    }
  } else {
    // console.log(1111, props.selectData)
    num.value = props.selectData ? props.selectData.length : 0
    selectData.value = props.selectData
    // console.log(selectData.value, 'assetsData.value')
    setTimeout(() => {
      if (selectData.value && selectData.value.length > 0) {
        selectData.value.forEach((row) => {
          multipleTable.value.toggleRowSelection(row, true)
        })
      } else {
        selectData.value = []
      }
    }, 0)
    await getList()
  }
}

init()

// 分页
const handleCurrentChange = (val) => {
  page.value = val
  getList()
  currentPage4.value = val
}

const handleSizeChange = () => {
  // console.log(`${val} items per page`)
  getList()
}

const getRowKeys = (row) => {
  return row.id
}
const handleSelect = (val) => {
  selectData.value = val
}
const select = (val, row) => {
  if (allCheck.value) {
    num.value = num.value - 1
    noSelectData.value.push(row)
    // console.log(noSelectData.value, 'noSelectData.value')
  } else {
    // console.log(val, 'val')
    num.value = val.length
    // console.log(selectData.value, 'selectData.value')
    selectData.value.filter((item, index) => {
      if (item.id == row.id) {
        // num.value = val.length
        selectData.value.splice(index, 1)
      } else {
        // num.value = val.length
      }
      // item.
    })
  }
}
// 全选当前页
const handleSelectAll = (val) => {
  num.value = selectData.value.length
  selectData.value = val
}
// 全选
const onChangeCheckAll = (val) => {
  if (val) {
    noSelectData.value = []
    // selectData.value = []
    num.value = total.value
    selectData.value.length = total.value
    assetsData.value.forEach((row) => {
      multipleTable.value.toggleRowSelection(row, true)
    })
  } else {
    num.value = 0
    multipleTable.value.clearSelection()
  }
}
defineExpose({
  selectData,
  noSelectData,
  allCheck
})

const ruleForm = reactive({
  pass: '',
  bread_sub: '',
  bread: ''
})

const rules = reactive({
  // pass: [{ validator: validatePass, trigger: 'blur' }],
  // checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  // age: [{ validator: checkAge, trigger: 'blur' }]
})

const submitForm = (formEl: FormInstance | undefined) => {
  // if (!formEl) return
  // formEl.validate((valid) => {
  //   if (valid) {
  //     console.log('submit!')
  //   } else {
  //     console.log('error submit!')
  //     return false
  //   }
  // })
  console.log(formEl, 'formEl')
  getList(ruleForm)
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

watch(
  () => multipleTable,
  (value) => {
    if (!value) return
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <div>
    <ElForm
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <ElFormItem class="formInput" label="牧场名称" prop="pasture_org_name">
        <ElInput v-model="ruleForm.pasture_org_name" placeholder="请输入" />
      </ElFormItem>
      <ElFormItem class="formInput" label="畜别" prop="breed_name">
        <ElSelect v-model="ruleForm.breed" @change="breedChange">
          <ElOption
            v-for="item in dict.breed"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem class="formInput" label="品种" prop="bread_sub_name">
        <ElSelect v-model="ruleForm.bread_sub">
          <ElOption
            v-for="item in breedSubData"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem class="formButton">
        <ElButton type="primary" @click="submitForm(ruleFormRef)" :icon="Search">查询</ElButton>
        <ElButton @click="resetForm(ruleFormRef)" :icon="RefreshLeft">重置</ElButton>
      </ElFormItem>
    </ElForm>
    <!-- <span>已选择 {{ num }}条资产</span> -->
    <ElTable
      ref="multipleTable"
      :data="assetsData"
      :row-key="getRowKeys"
      border
      @select-all="handleSelectAll"
      @selection-change="handleSelect"
      @select="select"
    >
      <ElTableColumn :value="selectData" type="selection" :reserve-selection="true" width="80" />
      <ElTableColumn
        prop="pasture_org_name"
        align="center"
        label="牧场"
        min-width="150px"
        show-overflow-tooltip
      />
      <ElTableColumn prop="id" align="center" label="id" min-width="150px" show-overflow-tooltip />
    </ElTable>

    <ElRow>
      <ElCol :span="3">
        <ElCheckbox class="mt-2px" @change="onChangeCheckAll" v-model="allCheck" label="全选所有" />
      </ElCol>
      <ElCol :span="4">
        <span>已选择 {{ num }}条资产</span>
      </ElCol>
      <ElCol class="text-left" :span="17">
        <ElPagination
          v-model:current-page="currentPage4"
          v-model:page-size="pageSize4"
          :page-sizes="[10, 50, 100, 1000]"
          :disabled="disabled"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-size="10"
          :total="total"
          style="float: right"
        />
      </ElCol>
    </ElRow>
  </div>
</template>
<style lang="less" scoped>
.demo-ruleForm .formInput {
  display: inline-flex;
  vertical-align: middle;
  margin-right: 32px;
}
:deep(.el-form-item__label) {
  width: 70px !important;
}
.formButton {
  display: inline-flex;
  vertical-align: middle;
}
.el-row .el-col-4 {
  line-height: 36px;
}
</style>
